package rs.networx.servlets;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.ejb.EJB;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

//import rs.networx.dao.NottificationCategory;
import rs.networx.dao.NottificationDao;
import rs.networx.dao.PersonDao;
//import rs.networx.dao.PostCategory;
import rs.networx.dao.PostDao;
import rs.networx.entity.Nottification;
import rs.networx.entity.Person;
import rs.networx.entity.Post;
import rs.networx.util.PropertiesUtil;

public class PostPictureOnMembersWallServlet extends HttpServlet {

	private static final long serialVersionUID = -1286135281349227612L;

	@EJB
	private PersonDao personDao;

	@EJB
	private NottificationDao nottificationDao;

	@EJB
	private PostDao postDao; 

	private String username;
	private String password;
	private Integer intLoggedUserID;
	private Person loggedUser;

	private String selectedPersonID;
	private Integer intSelectedPersonID;
	private Person selectedPerson;

	private String postTitlePicture;
	private String postTextPicture;

	private BufferedImage imageFromPost;
	private String imageNameFromPost;

	private String imageExtensionFromPost;
	private String imageNameForDBFromPost;

	private String propertyFile;
	private String networxDir;

	private Post picturePost;

	private Set<Person> selectedPersonsFriendsSet;
	private List<Person> selectedPersonsFriendsList;

	private Set<Person> loggedUsersFriendsSet;
	private List<Person> loggedUsersFriendsList;
	
	private ArrayList<Person> mutualFriends;

	private List<Post> selectedPersonsOwnedPosts;

	private Integer nottificationsCount;

	private boolean isMultipart;

	private boolean areFriends;
	
	private String cleanedUpDateOfBirth;

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		System.out.println("LOADED PostPictureLoggedUserOnMembersWallServlet");

		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding(response.getCharacterEncoding());

		HttpSession session = request.getSession();
		loggedUser = (Person)session.getAttribute("logovaniUser");

		/*// ovaj deo se radi dole u for petlji kada se kupe paramenti sa forme...
		// selectedPersonForMembersBrowsing...
		selectedPersonID = request.getParameter("personID");*/

		try {	
			username = loggedUser.getEmail();
			password = loggedUser.getPassword();
			intLoggedUserID = loggedUser.getId();
			System.out.println("loggedUser: " + username + "  " + password + "  " + intLoggedUserID);
		} catch (Exception e) {
			//e.printStackTrace();
		}

		if(loggedUser != null){
			try {
				// Check that we have a file upload request...
				isMultipart = ServletFileUpload.isMultipartContent(request);

				if(isMultipart){
					// Create a factory for disk-based file items...
					FileItemFactory factory = new DiskFileItemFactory();

					// Create a new file upload handler...
					ServletFileUpload upload = new ServletFileUpload(factory);

					// Parse the request...
					List<FileItem> items = upload.parseRequest(request);

					// getting all fields from form...
					for(FileItem fileItem : items){
						// if a form field...
						if(fileItem.isFormField()){
							if(fileItem.getFieldName().equals("personID")){
								selectedPersonID = fileItem.getString();
								System.out.println("selectedPersonID: " + selectedPersonID);

								// binding the personID parameter as atribute...
								request.setAttribute("personID", selectedPersonID);

								intSelectedPersonID = Integer.parseInt(selectedPersonID);
								System.out.println("intSelectedPersonID: " + intSelectedPersonID);
								continue;
							}
							if(fileItem.getFieldName().equals("postTitlePicture")){							
								postTitlePicture = fileItem.getString();
								System.out.println("postTitlePicture: " + postTitlePicture);
								continue;
							}
							if(fileItem.getFieldName().equals("postTextPicture")){							
								postTextPicture = fileItem.getString();
								System.out.println("postTextPicture: " + postTextPicture);
								continue;
							}
						}
						// if picture...
						if(!fileItem.isFormField()){
							imageFromPost = ImageIO.read(fileItem.getInputStream());
							imageNameFromPost = fileItem.getName();
							System.out.println("imageName: " + imageNameFromPost);						
						}
					}
				}

				if(intSelectedPersonID != null){
					// sada na osnovu intSelectedPersonID treba da nadjemo datog selectedPerson-a(selectedPersonForMembersBrowsing)...
					selectedPerson = personDao.findById(intSelectedPersonID);
					System.out.println("selectedPersonForMembersBrowsing: " + selectedPerson);

					if(selectedPerson != null){
						// creating new post...
						picturePost = new Post();
						picturePost.setTitle(postTitlePicture);
						picturePost.setText(postTextPicture);
						picturePost.setType(1);
						picturePost.setDate(Calendar.getInstance().getTime());

						// only temporary saving empty picture name...
						picturePost.setContent("");

						picturePost.setPoster(loggedUser);
						picturePost.setOwner(selectedPerson);

						// saving to generate the ID...
						postDao.persist(picturePost);

						imageExtensionFromPost = imageNameFromPost.substring(imageNameFromPost.lastIndexOf('.') + 1);
						imageNameForDBFromPost = picturePost.getId() + "." + imageExtensionFromPost;

						// setting image name and merging...
						picturePost.setContent(imageNameForDBFromPost);
						picturePost = postDao.merge(picturePost);
						System.out.println("New post: " + picturePost);

						// saving image in full size...
						propertyFile = getServletContext().getRealPath("networx.properties");
						networxDir = PropertiesUtil.getProperty(propertyFile, "networxDir");
						ImageIO.write(imageFromPost, imageExtensionFromPost, new File(networxDir + "/imagePost/" + imageNameForDBFromPost));
							
						// treba jos dodati i notifikaciju za selected persona da je dati loggedd user okacio novi picture post na selected persons wall...
						// adding nottification to selected person...
						Nottification nottification = new Nottification();
						nottification.setOwner(selectedPerson);
						nottification.setTargetID(picturePost.getId());
						nottification.setType(2);
						nottification.setViewed(false);
						nottification.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
								" target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
								" Added New Picture " + 
								"<i style=" + "\"" + "color: blue" + "\"" + ">" + postTitlePicture + "</i>" + 
						" To Your Wall.");	
						nottificationDao.persist(nottification);

						// treba dodati i notifikaciju za logged usera da je okacio novi picture post na selectedPersons wall...
						// adding nottification to logged user...
						Nottification nottification2 = new Nottification();
						nottification2.setOwner(loggedUser);
						nottification2.setTargetID(picturePost.getId());
						nottification2.setType(2);
						nottification2.setViewed(false);
						nottification2.setLink("You Added New Picture " + 
								"<i style=" + "\"" + "color: blue" + "\"" + ">" + postTitlePicture + "</i>" + 
								" To " + 
								"<a href=\"GoToSelectedPersonProfileServlet2?personID=" + selectedPerson.getId() + "\"" + 
								" target=\"_blank\"" + ">" + selectedPerson.getFirstName() + " " + selectedPerson.getLastName() + "'s" + "</a>" + 
						" Wall.");
						nottificationDao.persist(nottification2);

						// sada bi trebalo dodati i notifikaciju za svakog prijatelja selected persona da je logged user okacio novi picture post...
						// na selected persons wall...
						selectedPersonsFriendsSet = personDao.getFriends(intSelectedPersonID);
						System.out.println("selectedPersonsFriendsSet: " + selectedPersonsFriendsSet.size());

						if(selectedPersonsFriendsSet == null || selectedPersonsFriendsSet.size() == 0){
							// znaci da nema prijatelja, pa idemo dalje...
							System.out.println("selectedPersonsFriendsSet: " + selectedPersonsFriendsSet.size());

						}else if(selectedPersonsFriendsSet != null && selectedPersonsFriendsSet.size() > 0){
							selectedPersonsFriendsList = new ArrayList<Person>();

							Iterator<Person> iter = selectedPersonsFriendsSet.iterator();
							while(iter.hasNext()){
								selectedPersonsFriendsList.add((Person)iter.next());
							}
							System.out.println("selectedPersonsFriendsList: " + selectedPersonsFriendsList.size());

							// sada treba za svakog prijatelja selected persona da napravimo po notifikaciju...
							for(int i = 0; i < selectedPersonsFriendsList.size(); i++){
								// adding nottification to selected persons friends(koji nisu mutual friends)...
								if(selectedPersonsFriendsList.get(i).getId().equals(intLoggedUserID)){
									continue;
								}
								if(personDao.checkIfMutual(intSelectedPersonID, intLoggedUserID, selectedPersonsFriendsList.get(i).getId()) == false){
									
									Nottification nottification3 = new Nottification();
									nottification3.setOwner(selectedPersonsFriendsList.get(i));
									nottification3.setTargetID(picturePost.getId());
									nottification3.setType(2);
									nottification3.setViewed(false);
									nottification3.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
											" target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
											" Added New Picture " + 
											"<i style=" + "\"" + "color: blue" + "\"" + ">" + postTitlePicture + "</i>" + 
											" To " + 
											"<a href=\"GoToSelectedPersonProfileServlet2?personID=" + selectedPerson.getId() + "\"" + 
											" target=\"_blank\"" + ">" + selectedPerson.getFirstName() + " " + selectedPerson.getLastName() + "'s" + "</a>" + 
									" Wall.");
									nottificationDao.persist(nottification3);
								}
							}
						}

						// trebalo bi isto da napravimo i po notifikaciju za svakog prijatelja od logged usera da je dati logged user...
						// postovao link na selectedPersons wall...
						loggedUsersFriendsSet = personDao.getFriends(intLoggedUserID);
						System.out.println("loggedUsersFriendsSet: " + loggedUsersFriendsSet.size());

						if(loggedUsersFriendsSet == null || loggedUsersFriendsSet.size() == 0){
							// znaci da nema prijatelja, pa idemo dalje...
							System.out.println("loggedUsersFriendsSet: " + loggedUsersFriendsSet.size());

						}else if(loggedUsersFriendsSet != null && loggedUsersFriendsSet.size() > 0){
							loggedUsersFriendsList = new ArrayList<Person>();

							Iterator<Person> iter = loggedUsersFriendsSet.iterator();
							while(iter.hasNext()){
								loggedUsersFriendsList.add((Person)iter.next());
							}
							System.out.println("loggedUsersFriendsList: " + loggedUsersFriendsList.size());

							// sada treba za svakog prijatelja da napravimo po notifikaciju...
							for(int i = 0; i < loggedUsersFriendsList.size(); i++){
								// adding nottification to logged users friends(koji nisu mutual friends)...
								if(loggedUsersFriendsList.get(i).getId().equals(intSelectedPersonID)){
									continue;
								}
								if(personDao.checkIfMutual(intLoggedUserID, intSelectedPersonID, loggedUsersFriendsList.get(i).getId()) == false){
									
									Nottification nottification4 = new Nottification();
									nottification4.setOwner(loggedUsersFriendsList.get(i));
									nottification4.setTargetID(picturePost.getId());
									nottification4.setType(2);
									nottification4.setViewed(false);
									nottification4.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
											" target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
											" Added New Picture " + 
											"<i style=" + "\"" + "color: blue" + "\"" + ">" + postTitlePicture + "</i>" + 
											" To " + 
											"<a href=\"GoToSelectedPersonProfileServlet2?personID=" + selectedPerson.getId() + "\"" + 
											" target=\"_blank\"" + ">" + selectedPerson.getFirstName() + " " + selectedPerson.getLastName() + "'s" + "</a>" + 
									" Wall.");
									nottificationDao.persist(nottification4);
								}
							}
						}
						
						// sada treba i za sve mutual friends da posaljemo po notifikaciju...
						mutualFriends = personDao.getAllMutualFriends(intLoggedUserID, intSelectedPersonID);
						if(mutualFriends != null && mutualFriends.size() > 0){
							// saljemo notifikacije...
							System.out.println("mutualFriends: " + mutualFriends.size());
							
							for(int i = 0; i < mutualFriends.size(); i++){
								// adding notifications to all mutual friends...
								Nottification nottification4 = new Nottification();
								nottification4.setOwner(mutualFriends.get(i));
								nottification4.setTargetID(picturePost.getId());
								nottification4.setType(2);
								nottification4.setViewed(false);
								nottification4.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
										" target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
										" Added New Picture " + 
										"<i style=" + "\"" + "color: blue" + "\"" + ">" + postTitlePicture + "</i>" + 
										" To " + 
										"<a href=\"GoToSelectedPersonProfileServlet2?personID=" + selectedPerson.getId() + "\"" + 
										" target=\"_blank\"" + ">" + selectedPerson.getFirstName() + " " + selectedPerson.getLastName() + "'s" + "</a>" + 
								" Wall.");
								nottificationDao.persist(nottification4);
							}
						}else if(mutualFriends == null || mutualFriends.size() == 0){
							// ne saljemo nista...
							System.out.println("mutualFriends: " + mutualFriends.size());
						}

						// vidimo da li su logovani user i selected person za members browsing prijatelji, ako jesu tada logovani user moze da komentarise...
						// na zidu selected person za members browsing, a ako nisu onda ne moze...
						areFriends = personDao.areFriends(intLoggedUserID, intSelectedPersonID);
						System.out.println("areFriends: " + areFriends);

						// dobavljamo 10 postova za selektovanog korisnika(selectedPersonForMembersBrowsing) (ako ih ima)...
						selectedPersonsOwnedPosts = personDao.getFirstTenOwnedPosts(intSelectedPersonID);

						// sada dobavljamo i notifikacije za datog ulogovanog korisnika ako ih ima...
						nottificationsCount = nottificationDao.getNottificationsCountForLoggedUser(loggedUser);

						try {
							System.out.println("selectedPersonsOwnedPosts: " + selectedPersonsOwnedPosts.size());
							System.out.println("nottificationsCount: " + nottificationsCount);
						} catch (Exception e) {
							// 
							e.printStackTrace();
						}
						
						cleanedUpDateOfBirth = cleanUpDateOfBirth(selectedPerson.getDob());
						System.out.println(cleanedUpDateOfBirth);

						// postavljamo podatke na zahtev i na sesiju...
						request.setAttribute("selectedPersonForMembersBrowsing", selectedPerson);
						request.setAttribute("selectedPersonForMembersBrowsingPosts", selectedPersonsOwnedPosts);
						request.setAttribute("areFriends", areFriends);
						request.setAttribute("cleanedUpDateOfBirthForMembersBrowsing", cleanedUpDateOfBirth);

						// sada za logovanog korisnika postavljamo na sesiju nonviewed notifikacije (ako ih ima)...
						session.setAttribute("nottificationsCount", nottificationsCount);

						// redirektujemo na RegistredUserHomePageForMembers stranicu...
						RequestDispatcher disp = request.getRequestDispatcher("SelectedPersonPostsPage.jsp");
						disp.forward(request, response);
						
					}else if(selectedPerson == null){
						request.getRequestDispatcher("WelcomePage.jsp").forward(request, response);
						return;
					}
				}else if(intSelectedPersonID == null){
					request.getRequestDispatcher("WelcomePage.jsp").forward(request, response);
					return;
				}
			}catch (FileUploadException e){
				// 
				//e.printStackTrace();

				// obrada ako dodje do greske prilikom uploada slike...
				request.getRequestDispatcher("UploadPictureError.jsp").forward(request, response);
				return;
			}
		}else if(loggedUser == null){
			request.getRequestDispatcher("Welcome.jsp").forward(request, response);
			return;
		}	
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doGet(request, response);
	}
	
	private String cleanUpDateOfBirth(Date dateOfBirth){
		String result = null;
		
		if(selectedPerson != null){
			System.out.println(dateOfBirth);
			
			String dateOfBirthDB = dateOfBirth.toString();
			
			int i = dateOfBirthDB.indexOf(" ");
			System.out.println("i: " + i);
			
			String temp = dateOfBirthDB.substring(0, i);
			System.out.println("ddd: " + temp);
			
			String[] array = temp.split("-");
			
			System.out.println(array[0]);
			System.out.println(array[1]);
			System.out.println(array[2]);
			System.out.println(array[2] + "/" + array[1] + "/" + array[0]);
			
			result = array[2] + "/" + array[1] + "/" + array[0];
		}
		return result;
	}


}
